package com.xnyzc.lhy.order.service.impl.user.address;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.capi.collect.address.ECollectAddressType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.order.entity.address.collect.OaCAddressCollect;
import com.xnyzc.lhy.order.entity.address.collect.OaCSearchHistory;
import com.xnyzc.lhy.order.entity.param.user.address.UpdateAddressCollectParam;
import com.xnyzc.lhy.order.mapper.address.collect.OaCAddressCollectMapper;
import com.xnyzc.lhy.order.service.address.collect.IOaCSearchHistoryService;
import com.xnyzc.lhy.order.service.user.address.IOaCAddressCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 地点收藏 服务实现类
 * </p>
 *
 * @author bin
 * @since 2019-07-19
 */
@Service
public class OaCAddressCollectServiceImpl extends ServiceImpl<OaCAddressCollectMapper, OaCAddressCollect> implements IOaCAddressCollectService {

    @Autowired
    private OaCAddressCollectMapper oaCAddressCollectMapper;
    @Autowired
    private IOaCSearchHistoryService iOaCSearchHistoryService;

    /**
     * 删除地点
     * @param userId 用户id
     * @param tag 用户来源
     * @param updateAddressCollectParam 入参实体
     * @return
     */
    @Override
    public String deleteAddressCollect(Long userId, String tag, UpdateAddressCollectParam updateAddressCollectParam){
        List<OaCAddressCollect> oaCAddressCollects = oaCAddressCollectMapper.selectList(
                Wrappers.<OaCAddressCollect>lambdaQuery()
                        .eq(OaCAddressCollect::getTag, tag)
                        .eq(OaCAddressCollect::getUserId, userId)
                        .eq(OaCAddressCollect::getCollectType, updateAddressCollectParam.getType()));
        if (CheckUtil.objIsEmpty(oaCAddressCollects)){
            throw PangException.create(EErrorCode.addressDeleteFailure);
        }
        if (oaCAddressCollects.size() == 1){
            if (oaCAddressCollectMapper.deleteById(oaCAddressCollects.get(0).getCollectId()) != 1){
                throw PangException.create(EErrorCode.addressDeleteFailure);
            }
        } else {
            for (OaCAddressCollect oaCAddressCollect : oaCAddressCollects) {
                if (oaCAddressCollectMapper.deleteById(oaCAddressCollect.getCollectId()) != 1){
                    throw PangException.create(EErrorCode.addressDeleteFailure);
                }
            }
        }

        return EErrorCode.addressDeleteSuccess.getDesc();
    }

    /**
     * 更新地点收藏*
     * @param userId 用户id
     * @param tag 用户来源
     * @param updateAddressCollectParam 入参实体
     * @return
     */
    @Override
    public String updateAddressCollect(Long userId, String tag, UpdateAddressCollectParam updateAddressCollectParam){
        Date date = new Date();
        Integer type = updateAddressCollectParam.getType();
        List<OaCAddressCollect> oaCAddressCollects = oaCAddressCollectMapper.selectList(
                Wrappers.<OaCAddressCollect>lambdaQuery()
                        .eq(OaCAddressCollect::getCollectType, type)
                        .eq(OaCAddressCollect::getUserId, userId)
                        .eq(OaCAddressCollect::getTag, tag)
                        .orderByDesc(OaCAddressCollect::getCreateTime));
        // 新增
        if (CheckUtil.objIsEmpty(oaCAddressCollects)){
            OaCAddressCollect oaCAddressCollect = new OaCAddressCollect();
            oaCAddressCollect.setCollectId(IDUtil.nextId());
            oaCAddressCollect.setUserId(userId);
            oaCAddressCollect.setAddress(updateAddressCollectParam.getAddress());
            oaCAddressCollect.setLng(updateAddressCollectParam.getLng());
            oaCAddressCollect.setLat(updateAddressCollectParam.getLat());
            oaCAddressCollect.setCollectType(type);
            oaCAddressCollect.setTag(tag);
            oaCAddressCollect.setCreateUser(userId);
            oaCAddressCollect.setCreateTime(date);
            oaCAddressCollect.setUpdateUser(userId);
            oaCAddressCollect.setUpdateTime(date);
            if (oaCAddressCollectMapper.insert(oaCAddressCollect) != 1){
                throw PangException.create(EErrorCode.addressCollectFailure);
            }
        }
        // 修改
        else {
            // 修改第一条数据
            OaCAddressCollect oaCAddressCollect = oaCAddressCollects.get(0);
            oaCAddressCollect.setAddress(updateAddressCollectParam.getAddress());
            oaCAddressCollect.setLng(updateAddressCollectParam.getLng());
            oaCAddressCollect.setLat(updateAddressCollectParam.getLat());
            if (oaCAddressCollectMapper.updateById(oaCAddressCollect) != 1){
                throw PangException.create(EErrorCode.addressCollectFailure);
            }
            // 删除多余的数据
            for (int i = 1; i < oaCAddressCollects.size(); i++) {
                oaCAddressCollectMapper.deleteById(oaCAddressCollects.get(i));
            }
        }
        return EErrorCode.addressCollectSuccess.getDesc();
    }

    /**
     * 查询收藏地址*
     * @param userId 用户id
     * @param tag 用户来源
     * @return
     */
    @Override
    public Map<String, Object> getAddressCollect(Long userId, String tag){
        Map<String, Object> result = new HashMap<>(16);
        result.put("companyAddress", "");
        result.put("companyLng", "");
        result.put("companyLat", "");
        result.put("homeAddress", "");
        result.put("homeLng", "");
        result.put("homeLat", "");
        List<OaCAddressCollect> oaCAddressCollects = oaCAddressCollectMapper.selectList(
                Wrappers.<OaCAddressCollect>lambdaQuery()
                        .eq(OaCAddressCollect::getTag, tag)
                        .eq(OaCAddressCollect::getUserId, userId)
                        .orderByDesc(OaCAddressCollect::getCreateTime));
        for (OaCAddressCollect oaCAddressCollect : oaCAddressCollects) {
            Integer collectType = oaCAddressCollect.getCollectType();
            // 公司
            Object companyCollectId = result.get("companyCollectId");
            if (CheckUtil.objIsEmpty(companyCollectId) && ECollectAddressType.company.getValue().equals(collectType)){
                result.put("companyAddress", oaCAddressCollect.getAddress());
                result.put("companyLng", oaCAddressCollect.getLng());
                result.put("companyLat", oaCAddressCollect.getLat());
            }
            // 家
            Object homeCollectId = result.get("homeCollectId");
            if (CheckUtil.objIsEmpty(homeCollectId) && ECollectAddressType.home.getValue().equals(collectType)){
                result.put("homeAddress", oaCAddressCollect.getAddress());
                result.put("homeLng", oaCAddressCollect.getLng());
                result.put("homeLat", oaCAddressCollect.getLat());
            }
            if (CheckUtil.objIsNotEmpty(companyCollectId, homeCollectId)){
                break;
            }
        }
        return result;
    }

    /**
     * 用户收藏地址
     * @param userId 用户id
     * @param current 当前页
     * @param collectType 收藏地点类型（0：家、1：公司、2：其他）
     * @return
     */
    @Override
    public Map<String, Object> getAddressCollect(Long userId, long current, String... collectType) {
        QueryWrapper<OaCAddressCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("deleted", "0")
                .in("collect_type", collectType);
        List<OaCAddressCollect> oaCAddressCollects = oaCAddressCollectMapper.selectList(wrapper);
        Map<String, Object> result = new HashMap<>(7);
        if (oaCAddressCollects.size() <= 0){
            result.put("homeAddress", "");
            result.put("homeLng", "");
            result.put("homeLat", "");
            result.put("companyAddress", "");
            result.put("companyLng", "");
            result.put("companyLat", "");
        }
        for (OaCAddressCollect oaCAddressCollect : oaCAddressCollects) {
            if (ECollectAddressType.home.getValue().equals(oaCAddressCollect.getCollectType())){
                result.put("homeAddress", oaCAddressCollect.getAddress());
                result.put("homeLng", oaCAddressCollect.getLng());
                result.put("homeLat", oaCAddressCollect.getLat());
            }
            if (ECollectAddressType.company.getValue().equals(oaCAddressCollect.getCollectType())){
                result.put("companyAddress", oaCAddressCollect.getAddress());
                result.put("companyLng", oaCAddressCollect.getLng());
                result.put("companyLat", oaCAddressCollect.getLat());
            }
        }
        IPage<OaCSearchHistory> page = iOaCSearchHistoryService.selectHistoryAddressPage(userId, current);
        if (page.getRecords().size() <= 0){
            page.setRecords(new ArrayList<>());
        }
        result.put("historyAddress", page);
        return result;
    }
}
